<template>
  <div id="code-editor" ref="codeEditorRef" style="min-height: 500px" />
</template>

<script lang="ts" setup>
import message from "@arco-design/web-vue/es/message";
import * as monaco from "monaco-editor";
import { onMounted, ref, toRaw, withDefaults, defineProps, watch } from "vue";

/**
 * 定义组件类型
 */
interface Props {
  value: string;
  language?: string;
  questionId: number;
  handleChange: (v: string) => void;
}

/**
 * 给组件指定初始值
 */
const props = withDefaults(defineProps<Props>(), {
  value: () => "",
  language: () => "java",
  questionId: () => 0,
  handleChange: (v: string) => {
    console.log(v);
  },
});

const codeEditorRef = ref();
const codeEditor = ref();

//代码切换生效
watch(
  () => props.language,
  () => {
    if (codeEditor.value) {
      monaco.editor.setModelLanguage(
        toRaw(codeEditor.value).getModel(),
        props.language
      );
    }
  }
);

// watch(
//   () => props.value,
//   (newCode) => {
//     // 若组件未自动更新，可手动触发事件或调用组件方法
//     console.log("vlaue 已更新：", newCode);
//     // 调用 setValue 重新设置内容
//     // codeEditor.value?.setValue(props.value);
//     console.log("设置成功");
//   }
// );
onMounted(async () => {
  if (!codeEditorRef.value) {
    console.log("组件未加载");
    return;
  }

  codeEditor.value = monaco.editor.create(codeEditorRef.value, {
    value: props.value,
    language: props.language,
    automaticLayout: true,
    colorDecorators: true,
    minimap: {
      enabled: true,
    },
    // lineNumber: "off",
    // roundedSelection: false,
    // scrollBeyondLastLine: false,
    readOnly: false,
    theme: "vs-dark",
    autoClosingBrackets: "always", // 自动补全括号
    autoClosingQuotes: "always", // 自动补全引号
    acceptSuggestionOnEnter: "on", // 回车键接受建议
  });

  // 编辑监听内容变化
  codeEditor.value.onDidChangeModelContent(() => {
    props.handleChange(toRaw(codeEditor.value).getValue());
    console.log("目前内容未：", toRaw(codeEditor.value).getValue());
  });
  setTimeout(() => {
    console.log(".5秒后", props.value);
    toRaw(codeEditor.value).setValue(props.value);
  }, 500);
});
</script>

<style scoped></style>
